package com.ayic.garbagerecycle.controller;

import com.ayic.garbagerecycle.pojo.Station;
import com.ayic.garbagerecycle.pojo.Result;
import com.ayic.garbagerecycle.pojo.WasteRecord;
import com.ayic.garbagerecycle.pojo.WasteType;
import com.ayic.garbagerecycle.service.StationService;
import com.ayic.garbagerecycle.service.WasteService;
import java.util.Map;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequestMapping("/waste")
@RestController
public class WasteController {

    private static final Logger logger = LoggerFactory.getLogger(WasteController.class);

    @Resource
    private WasteService wasteService;
    @Resource
    private StationService stationService;

    @GetMapping("/records/{stationId}")
    public Result getWasteRecords(@PathVariable Integer stationId) {
        List<WasteRecord> records = wasteService.getWasteRecordsByStationId(stationId);
        return Result.success(records,"获取回收记录成功");
    }

    @PostMapping("/records/stationId")
    public Result addWasteRecord(@RequestBody Map<String, Object> requestBody) {
        logger.info("Received request body: {}", requestBody);

        WasteRecord wasteRecord = new WasteRecord();
        wasteRecord.setStationId(Integer.parseInt(requestBody.get("stationId").toString()));
        wasteRecord.setWeight(Integer.parseInt(requestBody.get("weight").toString()));
        wasteRecord.setVolume(Integer.parseInt(requestBody.get("volume").toString()));

        // 根据recognizedType查询对应的wasteType
        String recognizedType = (String) requestBody.get("recognizedType");
        if (recognizedType != null) {
            // 提取垃圾类型名称（去掉"可回收物_"前缀）
            String wasteTypeName = recognizedType.contains("_") ? 
                    recognizedType.substring(recognizedType.indexOf("_") + 1) : recognizedType;
            WasteType wasteType = wasteService.getWasteTypeByName(wasteTypeName);
            if (wasteType != null) {
                wasteRecord.setWasteType(wasteType.getWasteTypeId());
            } else {
                return Result.error("无法识别的垃圾类型：" + wasteTypeName);
            }
        } else {
            return Result.error("未提供垃圾类型信息");
        }

        Station station = stationService.getStationById(wasteRecord.getStationId());
        if (station == null) {
            return Result.error("找不到对应的站点信息");
        }

        // 检查站点容量
        if (station.getCurrentCapacity() + wasteRecord.getVolume() > station.getCapacity()) {
            return Result.error("超出站点容量");
        }

        // 设置用户ID并保存记录
        wasteRecord.setUserId(station.getUserId());
        Result result = wasteService.addRecord(wasteRecord, station.getUserId());

        // 检查记录是否成功添加且 wasteRecord 和 stationId 不为空，然后更新站点容量
        if (result.getCode() == 1 && wasteRecord.getStationId() != null) {
            stationService.updateCurrentCapacity(wasteRecord.getStationId());
        }

        return result;
    }

    @GetMapping("/queryType/{wasteType}")
    public String queryType(@PathVariable Integer wasteType) {
        return wasteService.queryType(wasteType);
    }
}